package dragon.social.core.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: Leo
 * @Date: 2020/3/16 22:28
 * 认证失败处理器
 * SimpleUrlAuthenticationFailureHandler是spring默认的失败处理器
 */
@Component("AuthenticationFailureHandler")
public class AuthFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Autowired
    ObjectMapper objectMapper;

    String returnType = "JSON";

    /**
     * springboot的工具，用于缓存请求
     */
    RequestCache requestCache = new HttpSessionRequestCache();

    Logger logger = LoggerFactory.getLogger(AuthFailureHandler.class);

//    public AuthFailureHandler() {
//        setDefaultFailureUrl("/failRedirect");
//    }

    /**
     * Performs the redirect or forward to the {@code defaultFailureUrl} if set, otherwise
     * returns a 401 error code.
     * <p>
     * If redirecting or forwarding, {@code saveException} will be called to cache the
     * exception for use in the target view.
     *
     * @param request
     * @param response
     * @param exception
     */


    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        SavedRequest savedRequest = requestCache.getRequest(request, response);
        logger.info("引发跳转的路径是：" + savedRequest.getRedirectUrl());
        //返回json数据
        if (returnType.equals("JSON")) {
            //设置返回码为500
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            String json = objectMapper.writeValueAsString(exception);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(json);
        }
        //使用默认的方式，即跳转到指定错误url
        else {
            super.onAuthenticationFailure(request, response, exception);
        }

    }
}
